//使用express内置中间件Router
let {Router} = require('express');
//使用path模块
let {resolve} = require('path');
//使用cookie-parser模块
let cookieParser = require('cookie-parser');
//使用userModel、kindModel数据模型
let userModel=require('../model/userModel');
let kindModel=require('../model/kindModel');
//创建一个路由器Router 与app类似
let router = new Router();
//使用cookie-parser中间件
router.use(cookieParser());

router.get('/index',async (req,res)=>{
    let {_id} = req.session;
    let user='';
    let dataSet=await kindModel.aggregate([
        {
            $lookup:{
                from:"goods",
                localField:"_id",
                foreignField:"kind_id",
                as:"goods"
            }
        }
    ]);
    if(_id){
        let result=await userModel.findOne({_id});
        user=result.user;
    }
    res.render('index',{user,dataSet})
});
router.get('/',(req,res)=>{
    console.log(req.headers["user-agent"])
    res.redirect('/index')
});
router.get('/index.html',(req,res)=>{
    res.redirect('/index')
});

router.get('/login',(req,res)=>{
    let user = req.query.user;
    res.render('login',{user})
});

router.get('/register',(req,res)=>{
    res.render('register',{})
});

router.get('/findpass',(req,res)=>{
    res.render('findpass',{})
});

router.get('/usercenter',async (req,res)=>{
    let {_id} = req.session;
    if(_id){
        let result=await userModel.findOne({_id});
        res.render('usercenter',{user:result.user})
    }else res.send(`<script>alert('您的身份已过期,请重新登录');window.location.href='http://127.0.0.1:8080/login'</script>`)

});
//暴露路由
module.exports = router;